package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
类简介：

功能：

时间：2020/4/2

*/
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        if (setmealDao.ifExit(setmeal) > 0){
            throw new RuntimeException("已经存在重复项");
        }else {
            if (setmealDao.add(setmeal) == 0){
                throw new RuntimeException("添加失败，请联系管理员");
            }else {
                for (Integer checkgroupId : checkgroupIds) {
                    if (setmealDao.addKey(setmeal.getId(),checkgroupId) == 0){
                        throw new RuntimeException("添加失败，请联系管理员");
                    }
                }
            }
        }

        generateMobileStaticHtml();

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage()<0?1:queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> setmeals;
        if (queryPageBean.getQueryString() != null){
            setmeals = setmealDao.findPage("%" + queryPageBean.getQueryString().trim() + "%");
            return new PageResult(setmeals.getTotal(),setmeals.getResult());
        }else {
            setmeals = setmealDao.findPage("%%");
            return new PageResult(setmeals.getTotal(),setmeals.getResult());
        }
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAllSetmeal();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //创建一个静态化页面的入口方法，供其他方法调用，在其中准备其他方法要用到的原始数据
    private void generateMobileStaticHtml(){

        //获取生成静态页面需要的数据
        List<Setmeal> setmealList = this.getAllSetmeal();

        //调用各自的生成静态页面的方法
        this.generateMobileSetmealListHtml(setmealList);
        this.generateMobileSetmealDetailHtml(setmealList);

    }

    //生成套餐静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList",setmealList);

        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);

    }

    //生成套餐详情页面
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {

        HashMap<String, Object> dataMap = new HashMap<>();

        for (Setmeal setmeal : setmealList) {
            dataMap.put("setmeal",this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+ setmeal.getId() + ".html",dataMap);
        }

    }


    @Autowired
    FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String outPutPath;
    //真正实现静态页面生成的方法
    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap){

        Configuration configuration = freeMarkerConfig.getConfiguration();

        Writer writer = null;

        try {
            Template template = configuration.getTemplate(templateName);

            File page = new File(outPutPath + htmlPageName);

            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(page), StandardCharsets.UTF_8));

            template.process(dataMap,writer);
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }


}
